<?php
ini_set('session.save_handler', 'user');
if (!class_exists('AoYunSession'))
{
	class AoYunSession implements SessionHandlerInterface
	{
		private static $handler = null;
		private static $table = '';
		public function close()
		{
			return true;
		}

		public function destroy ($session_id)
		{
			return self::$handler->query("DELETE FROM ".self::$table." WHERE sesskey='{$session_id}'");
		}

		public function gc ($maxlifetime)
		{
			return true;
		}

		public function open($save_path , $session_name)
		{
			global $db,$ecs;
			self::$handler = $db;
			self::$table = $ecs->table('app_sessions');
			return true;
		}

		public function read($session_id)
		{
			if (($data = self::$handler->getRow("SELECT data FROM".self::$table."WHERE sesskey='{$session_id}'"))===false)
			{
				$client_ip = IP;
				$session = [
					'sesskey' 	=> $session_id,
					'expiry' 	=> 0,
					'data' 		=> '',
					'ip' 		=> $client_ip,
					'user_id' 	=> 0
				];
				if (self::$handler->autoExecute(self::$table, $session, 'INSERT'))
				{
					return '';
				}
				else
				{
					abort(1);
				}
			}
			return $data['data'];
		}

		public function write($session_id , $session_data)
		{
			return self::$handler->autoExecute(self::$table, ['data' => $session_data], 'UPDATE', "sesskey='{$session_id}'");
		}
	}
	session_set_save_handler(new AoYunSession(), true);
}
